import React, { useEffect } from 'react';
import { BrowserRouter as Router, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, App as AntdApp, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { setMessageInstance } from '@/utils/request';
import { ErrorBoundary } from '@/utils/error-handler';
import { devTools } from '@/utils/dev-tools';

import MainLayout from '@/components/layout/MainLayout';
import Login from '@/pages/auth/Login';
import Dashboard from '@/pages/dashboard/Dashboard';
import NetworkTest from '@/pages/debug/NetworkTest';
import SetupMenuPage from '@/pages/test/SetupMenuPage';
import PermissionTestPage from '@/pages/test/PermissionTestPage';
import SetupAdminPermissionsPage from '@/pages/admin/SetupAdminPermissionsPage';
import NotFoundPage from '@/pages/error/NotFoundPage';
import DynamicRouteGuard from '@/components/route/DynamicRouteGuard';
import { useAuthStore } from '@/store/auth';
import { useUserStore } from '@/store/user';

const queryClient = new QueryClient();

const AppContent: React.FC = () => {
  const { isAuthenticated, token, clearAuth } = useAuthStore();
  const { getUserInfo } = useUserStore();
  const { message } = AntdApp.useApp();

  // 设置全局message实例
  useEffect(() => {
    setMessageInstance(message);
  }, [message]);

  useEffect(() => {
    if (token && !isAuthenticated) {
      getUserInfo().catch((error) => {
        // 只有在 401 错误时才清除认证状态
        if ((error as { response?: { status: number } })?.response?.status === 401) {
          clearAuth();
        }
      });
    }
  }, [token, isAuthenticated, getUserInfo, clearAuth]);

  const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    if (!isAuthenticated) {
      return <Navigate to="/login" replace />;
    }
    return <MainLayout>{children}</MainLayout>;
  };

  // 基础路由（不受权限控制）
  const basicRoutes = (
    <>
      <Route
        path="/login"
        element={isAuthenticated ? <Navigate to="/dashboard" replace /> : <Login />}
      />
      <Route
        path="/debug/network-public"
        element={<NetworkTest />}
      />
      <Route
        path="/"
        element={<Navigate to="/dashboard" replace />}
      />
    </>
  );

  // 需要权限保护的路由
  const protectedRoutes = (
    <>
      {/* dashboard 路由已移到动态路由中，避免冲突 */}
      <Route
        path="/test/setup-menu"
        element={
          <ProtectedRoute>
            <SetupMenuPage />
          </ProtectedRoute>
        }
      />
      <Route
        path="/test/permission"
        element={
          <ProtectedRoute>
            <PermissionTestPage />
          </ProtectedRoute>
        }
      />
      <Route
        path="/admin/setup-permissions"
        element={
          <ProtectedRoute>
            <SetupAdminPermissionsPage />
          </ProtectedRoute>
        }
      />
      <Route
        path="/404"
        element={<NotFoundPage />}
      />
      {/* 其他静态路由可以根据需要保留或移除 */}
    </>
  );

  return (
    <Router>
      <DynamicRouteGuard
        basicRoutes={basicRoutes}
        protectedRoutes={protectedRoutes}
      />
    </Router>
  );
};

const App: React.FC = () => {
  // 初始化开发工具
  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      devTools.recordPerformance('app_init', performance.now());
      console.log('[DevTools] Development tools initialized');
    }
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <ConfigProvider
        locale={zhCN}
        theme={{
          algorithm: theme.defaultAlgorithm,
          token: {
            colorPrimary: '#1890ff',
            borderRadius: 6,
          },
        }}
        message={{
          top: 100,
          duration: 3,
          maxCount: 3,
          fontSize: 16,
          radius: 8,
        }}
      >
        <AntdApp>
          <ErrorBoundary>
            <AppContent />
          </ErrorBoundary>
        </AntdApp>
      </ConfigProvider>
    </QueryClientProvider>
  );
};

export default App;
